<template>
	<view>
		<u-navbar
			bgColor="#2979ff"
			leftText="返回"
			title="个人中心"
			:titleStyle="titleColor"
			leftIcon="arrow-left"
			leftIconColor="white"
			:autoBack="true"
			:safeAreaInsetTop="true"
			:placeholder="true"
		>
			
		</u-navbar>
		<view class="font-typeface">
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u--form
					labelPosition="left"
					:model="model1"
					:rules="rules"
					ref="form1"
			>
				<!-- 联系方式 -->
				<u-form-item
						label="联系方式"
						labelWidth="80"
						prop="mobilePhone"	
						:borderBottom="false"
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="model1.mobilePhone"
							placeholder="请输入联系方式"
							border="none"
							:disabled="!isWrite"
							disabledColor="#fff"
					></u--input>
				</u-form-item>
				<!-- 维修地点 -->
				<u-form-item
						label="维修地点"
						labelWidth="80"
						prop="place"
						:borderBottom="false"
						@click="openSelect(0)"
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="model1.place"
							placeholder="  宜春学院"
							border="none"
							:disabled="!isWrite"
							disabledColor="#fff"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<!-- 详细地址 -->
				<u-form-item
						label="详细地址"
						labelWidth="80"
						prop="detailedAddress"
						:borderBottom="false"
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="model1.detailedAddress"
							border="none"
							placeholder="例: xxx楼层xxx室"
							:disabled="!isWrite"
							disabledColor="#fff"
					></u--input>
				</u-form-item>
				<!-- 维修类型 -->
				<u-form-item
						label="维修类型"
						labelWidth="80"
						prop="type"
						:borderBottom="false"
						@click="openSelect(1)"
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="model1.type"
							placeholder="请选择维修类型"
							border="none"
							:disabled="!isWrite"
							disabledColor="#fff"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<!-- 问题描述 -->
				<u-form-item
						label="问题描述"
						labelWidth="80"
						prop="questionDescription"
						:borderBottom="false"
						:required="true"
						ref="item1"
				>
					<u--textarea 
					v-model="model1.questionDetailed"
					confirmType="done"
					placeholder="请填写故障描述及上门维修的具体时间(温馨提示: 填写时间需精确到日期时分)" 
					:disabled="!isWrite"
					disabledColor="#fff"
					count ></u--textarea>
				</u-form-item>
				<!-- 故障图片 -->
				<u-form-item
						label="描述图片"
						labelWidth="80"
						prop="faultPicture"
						:borderBottom="false"
						ref="item1"
				>
					<u-upload
						:fileList="fileList"
						@afterRead="afterRead"
						@delete="deletePic"
						name="1"
						accept="image"
						multiple
						:disabled="!isWrite"
						:maxCount="10"
						:previewFullImage="true"
					></u-upload>
					<!-- <view class="picture-content" v-else>
						<u-album v-if="model1.urls.length>0" :urls="model1.urls" multipleSize="40" :space="4" ></u-album>
					</view> -->
				</u-form-item>
				
				</u-form-item>
				<!-- 维修进度 -->
				<u-form-item
						v-if="!isWrite"
						label="维修进度"
						labelWidth="80"
						:borderBottom="false"
						ref="item1"
				>
				</u-form-item>
			</u--form>
			<view v-if="!isWrite && model1.status!=3" style="margin-bottom: 50rpx;">
				<u-steps :current="model1.status+1">
					<u-steps-item title="开始提交" ></u-steps-item>
					<u-steps-item title="待处理" ></u-steps-item>
					<u-steps-item title="维修中" ></u-steps-item>
					<u-steps-item title="维修完成" ></u-steps-item>
				</u-steps>
			</view>
			
			<u-action-sheet
					:show="showSite"
					:actions="siteActions"
					title="请选择维修地点"
					@close="showSite = false"
					@select="siteSelect"
			>
			</u-action-sheet>
			<u-action-sheet
					:show="showType"
					:actions="typeActions"
					title="请选择维修类型"
					@close="showType = false"
					@select="typeSelect"
			>
			</u-action-sheet>
			<view class="ub-m" v-if="model1.status != 1 && model1.status != 2">
				<u-button color="#2979ff" v-if="isWrite" @click="submit">提交</u-button>
				<u-button color="#2979ff" v-else @click="isWrite=!isWrite">修改</u-button>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {getUploadToken, getDetails, commitMaintain, modifyMaintain} from '@/utils/api.js'
	export default {
		data() {
			return {
				titleColor:{'color':'white'},
				isWrite: true,
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				showSite: false,
				showType: false,
				fileList: [],
				token: '',
				lookImgPre: '',
				model1: {
					mobilePhone: '',
					place: '宜春学院',
					detailedAddress: '',
					type: '宿舍报修',
					questionDetailed: '',
					urls:[],
					status: 0,
				},
				siteActions: [
					{
						name: '宜春学院',
					},
				
				],
				typeActions: [
					{
						name: '宿舍报修',
					},
					{
						name: '网络维修',
					},
				
				],
				rules: {
					mobilePhone: [
						{
							type: 'string',
							required: true,
							message: '请填写手机号码',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],
					place: {
						type: 'string',
						max: 10,
						required: true,
						message: '请选择维修地点',
						trigger: ['blur', 'change']
					},
					type: {
						type: 'string',
						max: 10,
						required: true,
						message: '请选择维修类型',
						trigger: ['blur', 'change']
					},
					detailedAddress: {
						type: 'string',
						max: 30,
						required: true,
						message: '请填写详细地址',
						trigger: ['blur', 'change']
					},
					questionDetailed: {
						type: 'string',
						max: 140,
						required: true,
						message: '请填写故障描述',
						trigger: ['blur', 'change']
					},
					urls: {
						type: 'string',
						required: false,
					},
				},
			}
		},
		onLoad(option) { 
			console.log("onLoad: " + option.id) 
			if(option.id != null){
				//修改页面为读状态, 禁用输入
				this.isWrite = false;
				getDetails(option.id).then(res => {
					res.urls = res.urls!=null?res.urls.split(","):[]
					this.model1 = res
					for(let i=0; i<res.urls.length; i++){
						this.fileList.push({url: res.urls[i]})
					}
				})
			}
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
			this.getToken()
			
		},
		methods: {
			getToken(){
				getUploadToken().then(res=>{
					this.token = res.uploadToken
					this.lookImgPre = res.lookImgPre
				})
			},
			openSelect(i){
				if(this.isWrite){
					if(i == 0){
						this.showSite = true
					}else {
						this.showType = true
					}
				}
			},
			siteSelect(e) {
				this.model1.place = e.name
				//this.$refs.form1.validateField('site')
			},
			typeSelect(e) {
				this.model1.type = e.name
				//this.$refs.form1.validateField('site')
			},
			//表单校验
			submit() {
				const _that = this
				this.$refs.form1.validate().then(res => {
					let urls = _that.model1.urls
					let a = ''
					for(let i=0; i<urls.length; i++){
						a += _that.model1.urls[i] + ","
					}
					if(a.length > 1){
						_that.model1.urls = a.substr(0, a.length - 1)
					}
					if(_that.model1.id != null){	//更新
						modifyMaintain(_that.model1).then(res => {
							getApp().globalData.toast[0].message = '上报信息修改成功!'
							_that.$refs.uToast.show({
								...getApp().globalData.toast[0],
								complete() {
									//当前页
									let pages = getCurrentPages()
									//上个页面
									let beforePage = pages[pages.length - 2]
									let backUrl = beforePage.route
									uni.$u.route({
										type: 'redirect',
										url: backUrl,
									})
								}
							})
						})
					}else {	//提交
						commitMaintain(_that.model1).then(res => {
							getApp().globalData.toast[0].message = '提交上报信息成功!'
							_that.$refs.uToast.show({
								...getApp().globalData.toast[0],
								complete() {
									//当前页
									let pages = getCurrentPages()
									//上个页面
									let beforePage = pages[pages.length - 2]
									let backUrl = beforePage.route
									uni.$u.route({
										type: 'redirect',
										url: backUrl,
									})
								}
							})
						})
					}
					
				}).catch(errors => {
					getApp().globalData.toast[1].message = '提交的数据不合法!'
					_that.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {}
					})
				})
			},
			// 删除图片
			deletePic(event) {
				if(!this.isWrite) return
				this.fileList.splice(event.index, 1)
				this.model1.urls.splice(event.index, 1)
				console.log('this.model1.urls', this.model1.urls)
			},
			// 新增图片
			async afterRead(event) {
				const _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that.fileList.length
				//let fileListLen = _that[`fileList${event.name}`].length
				lists.map((item) => {
					_that.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that.fileList[fileListLen]
					if(result.hash != null){
						_that.model1.urls.push(_that.lookImgPre + result.key)
						_that.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '成功',
							url: _that.lookImgPre + result.key
						}))
						fileListLen++
					}else {
						getApp().globalData.toast[1].message = '图片上传失败!'
						_that.$refs.uToast.show({
							...getApp().globalData.toast[1],
							complete() {
								_that.fileList.splice(i, 1)
							}
						})
					}
					
				}
			},
			uploadFilePromise(url) {
				const that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://upload.qiniup.com/', 
						filePath: url,
						name: 'file',
						timeout: 5000,
						formData: {
							token: that.token,
							//key: url.substr(url.indexOf("0/") + 2)
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (error) => {
							console.log("错误!", error)
							resolve(error)
						}
					});
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.font-typeface{
		padding: 20rpx 20rpx;
	}
	.picture-content {
		margin-left: 28rpx;
		margin-top: 20rpx;
	}
	.ub-m{
		position: fixed;
		bottom: 2rpx;
		left: 0;
		width: 100%;
	}
</style>
